package com.shangsheng.role;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.io.IOException;
import java.util.Collection;

@Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private RedirectStrategy redirectStrategy= new DefaultRedirectStrategy();

    @Override
    protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String url="";
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        List<String> role =new ArrayList<>();
        for (GrantedAuthority grantedAuthority:authorities){
            role.add(grantedAuthority.getAuthority());
        }

        if (response.isCommitted()) {
            System.out.println("已经提交过了");
            return;
        }
        if (role.contains("ROLE_DBA")){
             url="/db";
        }else if (role.contains("ROLE_ADMIN")){
            url="/admin";
        }else if (role.contains("ROLE_USER")){
            url="/home";
        }else {
            url="/accessDenied";
        }
        redirectStrategy.sendRedirect(request,response,url);
    }
}
